package dormouse.vfs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;

import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;

/**
 * This class contains utilities for manipulating FileObjects.
 */
public class FileUtil {

	/**
	 * This method gets the subdirectories for a given directory.
	 * 
	 * @param dir
	 *            the directory
	 * @return
	 * @throws FileSystemException
	 */
	public static FileObject[] getChildDirectories(FileObject dir)
			throws FileSystemException {
		FileObject[] children = null;
		FileObject[] tempArray = null;
		tempArray = dir.getChildren();
		List<FileObject> fileArray = new ArrayList<FileObject>();
		for (int i = 0; i < tempArray.length; i++) {
			if (tempArray[i].getType() == FileType.FOLDER) {
				fileArray.add(tempArray[i]);
			}
		}
		children = new FileObject[fileArray.size()];
		children = (FileObject[]) fileArray.toArray(children);
		return children;
	}

	/**
	 * This method gets child files of a given extension.
	 * 
	 * @param fo
	 * @param ext
	 * @return
	 * @throws FileSystemException
	 */
	public static FileObject[] getChildrenByExtension(FileObject fo, String ext)
			throws FileSystemException {
		FileObject[] files = fo.getChildren();

		List<FileObject> fileList = new ArrayList<FileObject>();
		for (int i = 0; i < files.length; i++) {
			if (files[i].getName().getExtension().equalsIgnoreCase(ext)) {
				fileList.add(files[i]);
			}
		}
		FileObject[] filteredList = new FileObject[fileList.size()];
		fileList.toArray(filteredList);

		return filteredList;
	}

	/**
	 * Filters an array of file objects.
	 * 
	 * @param fileArray
	 *            an array of file objects
	 * @param predicate
	 *            the predicate used to filter the array
	 * @return a filtered array.
	 */
	public static List<FileObject> filterFileList(FileObject[] fileArray,
			Predicate<FileObject> predicate) {
		List<FileObject> fileList = Arrays.asList(fileArray);
		return filterFileList(fileList, predicate);
	}

	/**
	 * Filters a list of files
	 * 
	 * @param fileList
	 *            the list of files to be filtered
	 * @param predicate
	 *            the predicate used to filter the array
	 * @return a filtered array
	 */
	public static List<FileObject> filterFileList(List<FileObject> fileList,
			Predicate<FileObject> predicate) {
		if (predicate != null) {
			return new ArrayList<FileObject>(Collections2.filter(fileList,
					predicate));
		} else {
			return fileList;
		}
	}
	
	public static List<FileObject> createFileList(FileObject[] fileArray){
		return Arrays.asList(fileArray);
	}
}
